package com.example.huhaichao.fmusic.utils;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import com.example.huhaichao.fmusic.model.MusicModel;

import java.util.ArrayList;

/**
 * Created by huhaichao on 2017/10/12.
 * 初始化music信息
 */

public class MusicData {
    private ArrayList<MusicModel> musicList = new ArrayList();
    private Context context;

    public MusicData(Context context) {
        this.context = context;
        musicList = MusicList.getMusicList();
    }

    public void initMusicData() {
        if (musicList.isEmpty()) {
            Cursor mMusicCursor = context.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    }, null, null,
                    MediaStore.Audio.AudioColumns.TITLE
            );
            if (mMusicCursor != null) {
                //标题
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                //艺术家
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                //路径
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                //总时长
                int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);

                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strPath = mMusicCursor.getString(indexPath);
                    String strTotalTime = mMusicCursor.getString(indexTotalTime);

                    if (strArtist.equals("<unknown>"))
                        strArtist = "无艺术家";

                    MusicModel musicModel = new MusicModel(strTitle, strArtist, strPath, strTotalTime);
                    MusicList.addMusicList(musicModel);
                }
            }
        }
    }
}
